//
//  LSExportFilesViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2019/8/21.
//  Copyright © 2019 wpkj. All rights reserved.
//

#import "LSExportFilesViewController.h"
#import <QuickLook/QuickLook.h>

@interface LSExportFilesViewController () <UITableViewDelegate, UITableViewDataSource, UIWebViewDelegate, UIDocumentInteractionControllerDelegate, QLPreviewControllerDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableDictionary *localFile;
@property (nonatomic, strong) NZKNoDataView *nodataView;
@property (nonatomic, strong) NSMutableArray *selectedArrayM;
@property (nonatomic, copy) NSString *filePath;
@end

static NSString *LSExportFilesCellID = @"LSExportFilesCell";

@implementation LSExportFilesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"导出文件管理";
    [self.view addSubview:self.tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.localFile.count > 0) {
        [self.nodataView removeFromSuperview];
    } else {
        [self.view addSubview:self.nodataView];
    }
    return self.localFile.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSExportFilesCellID forIndexPath:indexPath];
    NSString *key = self.localFile.allKeys[indexPath.row];
    cell.textLabel.text = key;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    NSString *key = self.localFile.allKeys[indexPath.row];
    [self openDocxWithPath:self.localFile[key]];
//    [self openDocxWithQuickLookAtPath:self.localFile[key]];
}

- (void)openDocxWithQuickLookAtPath:(NSString *)filePath {
    self.filePath = filePath;
    QLPreviewController *previewController = [[QLPreviewController alloc] init];
    previewController.view.frame = self.view.bounds;
    previewController.dataSource = self;
    [self addChildViewController:previewController];
    [self.view addSubview:previewController.view];
}

- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller{
    return 1;
}
- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{
    //需要在线预览的文件的路径
    return [NSURL fileURLWithPath:self.filePath];
}

-(void)openDocxWithPath:(NSString *)filePath {
    NSString *codedFilePath = [filePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *fileUrl = [NSURL fileURLWithPath:codedFilePath];
    UIDocumentInteractionController *doc= [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:codedFilePath]];
    doc.delegate = self;
    if ([filePath hasSuffix:@"png"] || [filePath hasSuffix:@"PNG"] || [filePath hasSuffix:@"jpg"] || [filePath hasSuffix:@"JPG"] || [filePath hasSuffix:@"jpeg"] || [filePath hasSuffix:@"gif"] || [filePath hasSuffix:@"GIF"]) {
        [doc presentPreviewAnimated:YES];
    } else {
//        [doc presentOpenInMenuFromRect:CGRectMake(0, 0, ScreenWidth, ScreenHeight) inView:self.view animated:YES];
        NSData *xlsxData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:filePath]];
        UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:@[xlsxData,[NSURL fileURLWithPath:filePath]] applicationActivities:nil];
        [self presentViewController:activityController animated:YES completion:nil];
    }
//    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - SafeAreaTopHeight)];
//    webView.delegate = self;
//    webView.scalesPageToFit = YES;
//    [self.view addSubview:webView];
//    NSURL *url = [NSURL fileURLWithPath:filePath];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    [webView loadRequest:request];
}

#pragma mark - UIDocumentInteractionControllerDelegate
//必须实现的代理方法 预览窗口以模式窗口的形式显示，因此需要在该方法中返回一个view controller ，作为预览窗口的父窗口。如果你不实现该方法，或者在该方法中返回 nil，或者你返回的 view controller 无法呈现模式窗口，则该预览窗口不会显示。
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}

- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller {
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller {
    return CGRectMake(0, 30, ScreenWidth, ScreenHeight-SafeAreaTopHeight-30);
}

- (NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    WS
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        // 点击删除时 do something
        NSString *key = weakSelf.localFile.allKeys[indexPath.row];
        BOOL isRemove = [weakSelf removeDocumentWithFilePath:weakSelf.localFile[key]];
        if (isRemove) {
            [MBProgressHUD showTipMessageInWindow:@"移除成功"];
            [self.tableView reloadData];
        } else {
            [MBProgressHUD showTipMessageInWindow:@"移除失败"];
        }
    }];
    rowAction.backgroundColor = [UIColor redColor];
    NSArray *arr = @[rowAction];
    return arr;
}

- (BOOL)removeDocumentWithFilePath:(NSString*)filePath{
    BOOL isRemove = false;
    NSFileManager* fileManager = [NSFileManager defaultManager];
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        isRemove = [fileManager removeItemAtPath:filePath error:nil];
    }
    return isRemove;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:LSExportFilesCellID];
    }
    return _tableView;
}

- (NSMutableArray *)selectedArrayM {
    if (!_selectedArrayM) {
        _selectedArrayM = [[NSMutableArray alloc] init];
    }
    return _selectedArrayM;
}

-(NSMutableDictionary *)localFile {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    NSFileManager *fm = [NSFileManager defaultManager];
    NSDirectoryEnumerator *dirEnum = [fm enumeratorAtPath:[NSString stringWithFormat:@"%@/export",path]];
    NSString *fileName;
    NSMutableDictionary *R = [NSMutableDictionary dictionary];
    while (fileName = [dirEnum nextObject]) {
        NSString *key = [fileName componentsSeparatedByString:@"/"].lastObject;
        [R setObject:[path stringByAppendingPathComponent:[NSString stringWithFormat:@"export/%@",fileName]] forKey:key];
    }
    return R;
}

- (NZKNoDataView *)nodataView {
    if (!_nodataView) {
        _nodataView = [[NZKNoDataView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight) withTip:@"暂无相关信息" andButtonText:nil];
    }
    return _nodataView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
